
import json
from datetime import datetime

from django.http import JsonResponse
from django.views import View

from aijia_zufang.settings.dev import logger, QINIU_DOMIN_PREFIX
from aijia_zufang.utils.response_code import RET
from aijia_zufang.utils.views import LoginRequiredJSONMixin
from apps.house.models import House
from apps.orders.models import Order


class OrdersView(LoginRequiredJSONMixin, View):
    """
        客户订单接口文档
        请求方式：get
        请求路径：/api/v1.0/orders/
        请求参数：
        role     必传    string   custom:房客,landlord:房东
        响应：JSON
        {‘data’:{'orders:[{
         "amount": order.amount,
        "comment": order.comment,
        "ctime": order.create_time,
        "days": order.days,
        "end_date": order.end_date,
        "img_url": QINIU_DOMIN_PREFIX + str(order.house.index_image_url),
        "order_id": order.id,
        "start_date": order.begin_date,
        "status": stattus_data[1],
        "title": order.house.title
        },{},{}]'}}
        """

    def get(self, request):
        """
        客户订单接口文档
        请求方式：get
        请求路径：api/v1.0/orders/
        请求参数：role  str   必传   角色类型
        响应：JSON
        {‘data’：{‘orders:[{响应的参数},{},{}]’}}
        {响应的参数}=amount,comment,ctime,days,end_date,img_url,order_id,start_date,status,title
        """
        # 1.接受参数  用户
        user = request.user
        # 取当前角色的标识：房客：custom,房东：landlord
        role = request.GET.get("role")
        if role is None:
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})
        # 判断 role 是否是指定的值
        if role not in ("custom", "landlord"):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})
        try:
            if "custom" == role:  # 房客订单查询
                orders = Order.objects.filter(user=user).order_by('-create_time')
            elif "landlord" == role:  # 房东订单查询
                # 1. 先查出当前登录用户的所有的房屋, House
                houses = House.objects.filter(user=user)
                # 2. 取到所有的房屋id
                houses_ids = [house.id for house in houses]
                # 3. 从订单表中查询出房屋id在第2步取出来的列表中的房屋
                orders = Order.objects.filter(house_id__in=houses_ids).order_by('-create_time')
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': RET.DBERR, 'errmsg': "数据查询错误"})
        orders_dict_li = []
        for order in orders:
            orders_dict_li.append({
                "order_id": order.id,
                "title": order.house.title,
                "img_url": QINIU_DOMIN_PREFIX + order.house.index_image_url,
                "start_date": order.begin_date.strftime("%Y-%m-%d"),
                "end_date": order.end_date.strftime("%Y-%m-%d"),
                "ctime": order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                "days": order.days,
                "amount": order.amount,
                "status": order.status,
                "comment": order.comment
            })
        return JsonResponse({'errno': RET.OK, 'errmsg': "OK", 'data': {"orders": orders_dict_li}})



    '''
    添加订单接口文档
    请求方式：post
    请求路径：api/v1.0/orders/
    请求参数：
    house_id    int     必传    房屋id
    start_date  str     必传    开始日期
    end_date    str     必传    结束日期
    响应：errno:0-----errmsg:ok---------data:{order_id:1}
    '''

    def post(self, request):
        # 获取当前登录用户
        user = request.user
        # 1.接受参数
        user_dict = json.loads(request.body)
        house_id = user_dict.get('house_id')
        begin_date = user_dict.get('start_date')
        end_date = user_dict.get('end_date')
        # 2.校验参数
        if not all([house_id, begin_date, end_date]):
            return JsonResponse({'errno': RET.NODATA, 'errmsg': "参数不全"})
        # 3.业务逻辑
        # 3.1转换日期格式
        start_date =datetime.strptime(begin_date, '%Y-%m-%d')
        end_date = datetime.strptime(end_date, '%Y-%m-%d')
        # 计算入住天数
        days = (end_date - start_date).days
        # 判断入住天数是否有效
        if days < 0:
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': "参数错误"})
        # 3.2判断制定房屋是否存在
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': RET.NODATA, 'errmsg': "房屋不存在"})
        # 3.3判断订单用户是否为房主
        if house.user_id == user.id:
            return JsonResponse({'errno': RET.ROLEERR, 'errmsg': "不能预订自已的房屋"})
        # 3.4判断房屋是否已经出租
        count = Order.objects.filter(begin_date=begin_date, end_date=end_date, house_id=house_id).count()
        if count > 0:
            return JsonResponse({'errno': 400, 'errmsg': "房屋已经出租"})
        # 3.5添加用户订单
        try:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=begin_date,
                end_date=end_date,
                house_price=house.price,
                days=days,
                amount=days*house.price,

            )
        except Exception as e:
            logger(e)
            return JsonResponse({'errno': RET.DBERR, 'errmsg': "生成订单失败"})
        # 4.返回
        order_id = order.id
        data = {
            "order_id": order_id,
        }
        return JsonResponse({'errno': 0, 'errmsg': "ok", 'data': data})
    # 接单/拒单
    def put(self, request):
        """
        订单接单拒单接口文档
        请求方式: put
        请求路径: api/v1.0/orders/
        请求参数: action,必传,str类型,操作类型：[accept: 接单，reject：拒单]
                 order_id,必传,int类型,订单号
                 reason,非必传,str类型,拒单时，需要填写拒单原因
        返回结果:json  {'errno': 0 , 'errmsg': 'OK'}
        """
        # 1.接收参数
        json_dict = json.loads(request.body)
        # 2.解析参数

        # 获取到订单号
        order_id = json_dict.get('order_id')
        # 获取到订单的接单拒单
        action = json_dict.get('action')

        # 3.校验参数

        # 判断参数是否为空
        if not all([order_id, action]):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数不能为空'})

        # 判断如果action里没有 接单拒单两个参数
        if action not in ('accept', 'reject'):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数错误'})
        # 查询订单
        try:
            order = Order.objects.get(pk=order_id, status='WAIT_ACCEPT')
        except:
            return JsonResponse({'errno': RET.NODATA, 'errmsg': '未查询到订单'})

        # 判断当前订单的房东是否的当前用户
        if request.user != order.house.user:
            return JsonResponse({'errno': RET.ROLEERR, 'errmsg': '用户身份错误'})
        # 4.修改订单状态

        if 'accept' == action:
            # 如果接单了,就把订单状态改为待评价
            order.status = "WAIT_COMMENT"
        elif 'reject' == action:
            # 如果拒单了,就把订单状态改为已拒单,并且要写入拒绝原因
            order.status = 'REJECTED'

            # 拒单原因
            reason = json_dict.get('reason')
            # 如果reason没有内容
            if not reason:
                return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '请填写拒单原因'})
            # 保存拒单原因
            order.comment = reason

        # 5.保存到数据库
        try:
            # 提交
            order.save()
        except:
            return JsonResponse({'errno': RET.DBERR, 'errmsg': "提交失败"})

        # 6.返回
        return JsonResponse({'errno': RET.OK, 'errmsg': 'OK'})





class OrdersCommentView(View):
    # 评价订单
    def put(self, request):
        """
        评价订单接口文档
        请求方式: put
        请求路径: api/v1.0/orders/comment/
        请求参数: comment,必传,str类型,评论内容
                 order_id,必传,int类型,订单号
        返回响应: json   {'errno': 0 , 'errmsg': 'OK'}
        """
        # 1.获取参数
        json_dict = json.loads(request.body)
        comment = json_dict.get('comment')
        order_id = json_dict.get('order_id')
        # 2.校验参数

        # 判断参数是否为空
        if not all([comment, order_id]):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '参数不能为空'})

        try:
            # 查询订单(状态:待评价的订单)
            order = Order.objects.get(pk=order_id, status="WAIT_COMMENT")
        except:
            return JsonResponse({'errno': RET.DBERR, 'errmsg': '订单不存在'})
        # 3.把评价保存到数据库,并且修改状态
        order.comment = comment
        order.status = "COMPLETE"
        # 4.保存到数据库
        try:
            # 提交
            order.save()
        except:
            return JsonResponse({'errno': RET.DBERR, 'errmsg': "提交失败"})
        # 5.返回
        return JsonResponse({'errno': RET.OK, 'errmsg': 'OK'})
